from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from fastapi.openapi.utils import get_openapi
import os
from routers import auth
from routers import upload
from routers import tools
from routers import competition
from routers import admin
from routers import levels
from routers import score_dimensions
from routers import analytics
from routers import site
from routers import config

# 创建FastAPI应用实例
app = FastAPI(
    title="AIGD100 API",
    description="AIGD100项目的API接口",
    version="1.0.0",
    docs_url=None,
    redoc_url=None,
    openapi_version="3.0.3",
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建上传目录
os.makedirs("uploads", exist_ok=True)
os.makedirs("uploads/avatars", exist_ok=True)
os.makedirs("uploads/files", exist_ok=True)
os.makedirs("uploads/icon", exist_ok=True)
os.makedirs("uploads/images", exist_ok=True)

# 配置静态文件服务
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
app.mount("/icon", StaticFiles(directory="uploads/icon"), name="icon")
app.mount("/images", StaticFiles(directory="uploads/images"), name="images")
app.mount("/avatars", StaticFiles(directory="uploads/avatars"), name="avatars")
os.makedirs("static/docs", exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")

app.include_router(auth.router, prefix="/v1")
app.include_router(upload.router, prefix="/v1")
app.include_router(tools.router, prefix="/v1")
app.include_router(competition.router, prefix="/v1")
app.include_router(admin.router, prefix="/v1")
app.include_router(levels.router, prefix="/v1")
app.include_router(score_dimensions.router, prefix="/v1")
app.include_router(analytics.router, prefix="/v1")
app.include_router(site.router, prefix="/v1")
app.include_router(config.router, prefix="/v1")

from database.connection import create_database

def init_database() -> None:
    """
    在应用启动阶段初始化数据库表
    如果表不存在则根据已加载的 ORM 模型创建
    """
    create_database()

init_database()

@app.get("/")
async def root():
    """
    根路径健康检查接口
    返回API的基本信息
    """
    return {
        "message": "AIGD100 API is running",
        "version": "1.0.0",
        "status": "healthy"
    }

@app.get("/health")
async def health_check():
    """
    健康检查接口
    用于监控服务状态
    """
    return {"status": "healthy"}


@app.get("/docs")
async def custom_swagger_ui():
    """
    返回使用本地静态资源的 Swagger UI 文档页
    """
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - 文档",
        swagger_js_url="/static/docs/swagger-ui-bundle.js",
        swagger_css_url="/static/docs/swagger-ui.css",
    )


@app.get("/redoc")
async def custom_redoc():
    """
    返回使用本地静态资源的 Redoc 文档页
    """
    return get_redoc_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - Redoc",
        redoc_js_url="/static/docs/redoc.standalone.js",
    )


def custom_openapi():
    """
    生成 OpenAPI Schema（强制设置为 3.0.3 以兼容本地 Swagger UI）
    """
    openapi_schema = get_openapi(
        title=app.title,
        version=app.version,
        description=app.description,
        routes=app.routes,
    )
    openapi_schema["openapi"] = "3.0.3"
    return openapi_schema


app.openapi = custom_openapi


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
